<?php

namespace App\Http\Controllers;

use App\Models\Bookmark;
use Illuminate\Http\Request;
use Jiannei\Response\Laravel\Support\Facades\Response;
use App\Http\Requests\BookmarkRequest;
use App\Http\Resources\BookmarkResource;

class BookmarkController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // Laravel 的分页， 参数 size 是指每页查询多少条数据。还有另外一个参数 page ，会自动检测。
        // 请求示例：GET  /bookmarks?size=3&page=1
        $size = $request->query('size');
        $request->validate([
            'size' => 'nullable|numeric',
            'page' => 'nullable|numeric',
        ]);
        $bookmarks = Bookmark::where('status',1)->paginate($size);
        return Response::success(BookmarkResource::collection($bookmarks));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(BookmarkRequest $request)
    {
        $request->validated();

        $bookmark = Bookmark::create($request->all());
        // 返回创建完成的 Bookmark 实例
        return Response::success(new BookmarkResource($bookmark));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Bookmark  $bookmark
     * @return \Illuminate\Http\Response
     */
    public function show(Bookmark $bookmark)
    {
        // $userArr = User::find($bookmark->user_id)->toArray();
        // $bookmarkArr = $bookmark->toArray();
        // $bookmarkArr['user'] = $userArr;
        // $result = array_merge($bookmarkArr, $userArr);
        return Response::success(new BookmarkResource($bookmark));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Bookmark  $bookmark
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Bookmark $bookmark)
    {
        //
        $bookmark->update($request->all()); //返回 boolean 值
        return Response::success($bookmark);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Bookmark  $bookmark
     * @return \Illuminate\Http\Response
     */
    public function destroy(Bookmark $bookmark)
    {
        $bookmark->delete(); // 返回 boolean 值
        return Response::success($bookmark);
    }
}
